package com.tiyende.credit.loop.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.lib.common.shapeview.layout.ShapeLinearLayout
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.configs.TiyendeApiPath
import com.tiyende.credit.loop.configs.TiyendeApiUrl
import com.tiyende.credit.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.credit.loop.databinding.TiyendeActivityAuthenticationAccountCreateBinding
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.event.TiyendeEventData
import com.tiyende.credit.loop.request.IHttpCallback
import com.tiyende.credit.loop.ui.dialog.TiyendeAccountBindOtherDialog
import com.tiyende.credit.loop.utils.TiyendeDensityUtil
import com.tiyende.credit.loop.utils.TiyendeImageUtil
import com.tiyende.credit.loop.utils.decoration.LinearSpacingItemDecoration
import com.tiyende.credit.loop.utils.helper.TiyendeConfigsHelper
import com.tiyende.credit.loop.weight.font.RobotoMediumEditText
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/21 13:45
 * @Annotation：新包绑卡
 */
class TiyendeAuthenticationAccountCreateActivity: CommonActivity() {
    private lateinit var binding: TiyendeActivityAuthenticationAccountCreateBinding
    private var itemAdapter: ItemAdapter? = null

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityAuthenticationAccountCreateBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeBackBtnRes(R.mipmap.tiyende_back_white)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeTextTitleVisibility(View.GONE)

        initWalletTypeListView()
        showTypeDefaultView()
        checkSubmitStatus()
    }

    override fun initTiyendeListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Account Add Page")
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,"Account Add Page")
        }
        binding.walletMobile.addTextChangedListener(ITextWatcher)
        binding.walletMobileAgain.addTextChangedListener(ITextWatcher)
        binding.walletMobile.setInputFocusChangeListener(IEditFocusChangeListener)
        binding.walletMobileAgain.setInputFocusChangeListener(IEditFocusChangeListener)
        binding.walletMobile.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.walletMobile.clearFocus()
                true
            }
            false
        }
        binding.walletMobileAgain.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.walletMobileAgain.clearFocus()
                true
            }
            false
        }
        binding.walletSubmit.setOnClickListener {
            val typeObj = getSelectTypeItem() ?: return@setOnClickListener
            if (getPhoneNumber() != getPhoneNumberComplete()){
                showTypeErrorView()
                return@setOnClickListener
            }
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_ACCOUNT_ADD_SUBMIT,getPhoneNumber())
            onSunmitAuthStepWalletAddAction(getPhoneNumber(),typeObj.optString("value"))
        }
    }

    override fun loadTiyendeData() {
        val bindList = arrayListOf<JSONObject>()
        val customize = TiyendeConfigsHelper.queryTiyendeConfigData()
        if (customize != null){
            val walletChannels = customize.optJSONArray("walletChannels")
            if (walletChannels != null && walletChannels.length() > 0){
                for (i in 0..<walletChannels.length()){
                    val item = walletChannels.optJSONObject(i)
                    item.put("isSelect", false)
                    bindList.add(item)
                }
            }
        }
        itemAdapter?.data = bindList
    }

    /**
     * 初始化类型列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initWalletTypeListView() {
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.walletTypeListView.layoutManager = layoutManager
        itemAdapter = ItemAdapter(binding.walletTypeListView)
        val leftDecoration = TiyendeDensityUtil.dp2px(10f)
        binding.walletTypeListView.addItemDecoration(LinearSpacingItemDecoration(0, leftDecoration,0,0))
        binding.walletTypeListView.adapter = itemAdapter
        binding.walletTypeListView.itemAnimator = DefaultItemAnimator()
        itemAdapter?.setOnItemChildClickListener { _, childView, position ->
            val model = itemAdapter?.getItem(position)
            if (childView.id == R.id.walletItem) {//切换item
                itemAdapter?.let {
                    for (i in 0..< it.itemCount) {
                        val item = it.getItem(i)
                        if (i == position) {
                            item.put("isSelect", true)
                        } else {
                            item.put("isSelect", false)
                        }
                    }
                    it.notifyDataSetChanged()
                }
                checkSubmitStatus()
                model?.let {
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_ACCOUNT_ADD_TYPE_CHECK, it.optString("desc"))
                }
            }
        }
    }

    /**
     * 输入框监听
     */
    private val ITextWatcher = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            showTypeDefaultView()
            checkSubmitStatus()
        }
    }

    /**
     * 焦点变化监听
     */
    private val IEditFocusChangeListener = object : RobotoMediumEditText.IInputFocusChangeListener{
        override fun onFocusChange(v: View?, hasFocus: Boolean) {
        }

        override fun onCompleteAction(v: View?, remark: String?) {
            if (v?.id == R.id.walletMobile){
                val mobile = binding.walletMobile.text.toString().trim()
                if (mobile.isNotEmpty()){
                    addEventPointRequestAction(TiyendeEventPointType.FORM.TIYENDE_FORM_USER_ACCOUNT_ADD_MOBILE,remark)
                }
            } else {
                val mobile = binding.walletMobileAgain.text.toString().trim()
                if (mobile.isNotEmpty()){
                    addEventPointRequestAction(TiyendeEventPointType.FORM.TIYENDE_FORM_USER_ACCOUNT_ADD_MOBILE,remark)
                }
            }
        }
    }

    /**
     * 设置默认样式
     */
    private fun showTypeDefaultView(){
        binding.tiyendeAccountMobileLayout1.shapeDrawableBuilder.setStrokeColor(Color.parseColor("#FF334155")).intoBackground()
        binding.walletMobile.setTextColor(Color.parseColor("#FFFFFFFF"))
        binding.tiyendeAccountMobileLayout2.shapeDrawableBuilder.setStrokeColor(Color.parseColor("#FF334155")).intoBackground()
        binding.walletMobileAgain.setTextColor(Color.parseColor("#FFFFFFFF"))
        binding.tiyendeAccountErrorLayout.visibility = View.INVISIBLE

        if (getPhoneNumber().isNotEmpty()){
            binding.imageAccountEditIcon1.visibility = View.INVISIBLE
        } else {
            binding.imageAccountEditIcon1.visibility = View.VISIBLE
        }
        if (getPhoneNumberComplete().isNotEmpty()){
            binding.imageAccountEditIcon2.visibility = View.INVISIBLE
        } else {
            binding.imageAccountEditIcon2.visibility = View.VISIBLE
        }
    }

    /**
     * 设置号码错误提示
     */
    private fun showTypeErrorView(){
        binding.tiyendeAccountMobileLayout1.shapeDrawableBuilder.setStrokeColor(Color.parseColor("#FFF36767")).intoBackground()
        binding.walletMobile.setTextColor(Color.parseColor("#FFFFFFFF"))
        binding.tiyendeAccountMobileLayout2.shapeDrawableBuilder.setStrokeColor(Color.parseColor("#FFF36767")).intoBackground()
        binding.walletMobileAgain.setTextColor(Color.parseColor("#FFFFFFFF"))
        binding.tiyendeAccountErrorLayout.visibility = View.VISIBLE
    }

    /**
     * 切换Ajouter按钮是否可点击
     */
    fun checkSubmitStatus(){
        if (getSelectTypeItem() != null && getPhoneNumber().isNotEmpty() && getPhoneNumberComplete().isNotEmpty() && (getPhoneNumber() == getPhoneNumberComplete())){
            binding.walletSubmit.isEnabled = true
        } else {
            binding.walletSubmit.isEnabled = false
        }
    }

    /**
     * 获取选择的账户类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var obj: JSONObject? = null
        itemAdapter?.let {
            for (item in it.data) {
                if (item.optBoolean("isSelect", false)){
                    obj = item
                    break
                }
            }
        }
        return obj
    }

    /**
     * 获取输入的手机号码
     */
    private fun getPhoneNumber(): String{
        return binding.walletMobile.text.toString()
    }

    /**
     * 获取确认手机号码
     */
    private fun getPhoneNumberComplete(): String{
        return binding.walletMobileAgain.text.toString()
    }

    fun showAuthStepWalletOtherDialog(otherInfo: JSONObject) {
        val bindOtherDialog = TiyendeAccountBindOtherDialog(this,object : TiyendeAccountBindOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.walletOtherConfirm){//添加
                    onSunmitAuthStepWalletAddAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                } else {
                    finish()
                }
            }
        })
        bindOtherDialog.setCancelable(true)
        bindOtherDialog.setCanceledOnTouchOutside(false)
        bindOtherDialog.show()
        bindOtherDialog.setBindAccountInfo(otherInfo)
    }

    class ItemAdapter(recyclerView: RecyclerView?) : CommonRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.tiyende_activity_authentication_account_type_item) {
        override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.walletItem) //点击Item
        }
        override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
            val isSelect = model.optBoolean("isSelect", false)
            val walletItem = helper.getView<ShapeLinearLayout>(R.id.walletItem)
            val walletLogo = helper.getImageView(R.id.walletLogo)
            val walletTitle = helper.getTextView(R.id.walletTitle)
            walletTitle.text = model.optString("desc")
            TiyendeImageUtil.instance?.loadImageUrl(mContext,walletLogo,model.optString("logo"), R.mipmap.tiyende_holder)

            if (isSelect) {
                walletItem.shapeDrawableBuilder.setStrokeColor(Color.parseColor("#FF3ED9AB")).intoBackground()
                walletTitle.setTextColor(Color.parseColor("#FFFFFFFF"))
            } else {
                walletItem.shapeDrawableBuilder.setStrokeColor(Color.parseColor("#FF334155")).intoBackground()
                walletTitle.setTextColor(Color.parseColor("#FFFFFFFF"))
            }
        }
    }

    /**
     * 添加绑卡
     */
    private fun onSunmitAuthStepWalletAddAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        showTiyendeLoading()
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_ACCOUNT_ADD_PATH)
            put("walletMobile", mobile)
            put("walletMobileConfirm", mobile)
            put("walletChannel", walletChannel)
            put("addBindFlag", bindFlag)
        }

        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_WALLET_REFRESH))
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()
                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val customize = TiyendeConfigsHelper.queryTiyendeConfigData()
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        showAuthStepWalletOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        } else {
                            hiddenTiyendeLoading()
                            finish()
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        showTiyendeToast(msg)
                        showTypeErrorView()
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hiddenTiyendeLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.DIALOG.TIYENDE_DIALOG_USER_ACCOUNT_ADD_SHOW)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.DIALOG.TIYENDE_DIALOG_USER_ACCOUNT_ADD_DISMISS)
    }
}